package com.uxsino.simo.incremental.parser;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uxsino.reactorq.model.IndicatorValue;
import com.uxsino.simo.incremental.IncrementalParser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Auther dousil
 * @Data   2020-06-17
 */
public class TPSParser implements IncrementalParser {

    private static final Logger logger = LoggerFactory.getLogger(TPSParser.class);

    //计算允许最小时间间隔
    private final static int MIN_INTERVAL =60;

    @Override
    public void apply(IndicatorValue oldValue, IndicatorValue value){

        if(null == value){
            logger.info("indicatorName ---->{},entityId--->{} value is null",value.indicatorName,value.entityId);
        }else if(null == oldValue&&value.value!=null){
            /**
             * formula   vallue.tps/uptime
             */
            Object obj = JSONArray.toJSON(value.value);
            //1 取出tps,qps,uptime
            //3. 存入value
            if(obj instanceof JSONObject){
                JSONObject json = (JSONObject)obj;
                double tps = json.getDouble("tpsall")/json.getDouble("uptime");
                double qps = json.getDouble("questions")/json.getDouble("uptime");
                json.put("tps",tps);
                json.put("qps",qps);
                value.value = json;
                System.out.println("dousil:   value.value");
            }else{
                logger.warn("indicator ---->{} is not compound type",value.indicatorName);
            }
        }else{
            /**
             * formula (value.tps--oldValue.tps)/(value.uptime-oldvallue.uptime)
             */
            JSONObject nowjsonarray = (JSONObject)JSONArray.toJSON(value.value);
            JSONObject oldjsonarray = (JSONObject)JSONArray.toJSON(oldValue.value);
            double tps = (nowjsonarray.getDouble("tpsall")-oldjsonarray.getDouble("tpsall"))/(nowjsonarray.getDouble("uptime")-oldjsonarray.getDouble("uptime"));
            double qps = (nowjsonarray.getDouble("questions")-oldjsonarray.getDouble("questions"))/(nowjsonarray.getDouble("uptime")-oldjsonarray.getDouble("uptime"));
            nowjsonarray.put("tps",tps);
            nowjsonarray.put("qps",qps);
            value.value = nowjsonarray;
        }
    }
}
